package com.cq.cqmall.product.web;

import com.cq.cqmall.product.entity.CategoryEntity;
import com.cq.cqmall.product.service.CategoryService;
import com.cq.cqmall.product.vo.Catalog2VO;
import org.redisson.api.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 索引页控制器
 *
 * @author 程崎
 * @since 2022/10/12
 */
@Controller
public class IndexController {

    @Resource
    private CategoryService categoryService;

    @Resource
    private RedissonClient redisson;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping({"/", "index", "/index.html"})
    public String indexPage(Model model) {
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categories();
        model.addAttribute("categories", categoryEntities);
        return "index";
    }

    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2VO>> getCatalogJson() {
        return categoryService.getCatalogJson();
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {

        RLock lock = redisson.getLock("my-lock");
        lock.lock();
        try {
            System.out.println("加锁成功，执行业务:" + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("释放锁:" + Thread.currentThread().getId());
            lock.unlock();
        }
        return "<h1>hello</h1>";
    }

    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.writeLock();
        String s = "";
        try {
            s = UUID.randomUUID().toString();
            rLock.lock();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.readLock();
        rLock.lock();
        String value = null;
        try {
            value = stringRedisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }
        return value;
    }

    /**
     * 停车
     * 3号车位
     *
     * @return {@link String}
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() {
        RSemaphore park = redisson.getSemaphore("park");
        // 获取一个信号，获取一个值，占一个车位
        boolean b = park.tryAcquire();
        if (b) {
            // do work
            return "ok";
        }else {
            return "当前流量过大，请稍等";
        }
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() {
        RSemaphore park = redisson.getSemaphore("park");
        // 释放一个车位
        park.release();
        return "ok";
    }

    /**
     * 放假，锁门
     * 5个班全部走完才可以锁门
     *
     * @return {@link String}
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();
        return "放假了";
    }

    @GetMapping("/go/{id}")
    @ResponseBody
    public String go(@PathVariable Long id) {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();
        return id + "班的人走了";
    }

}
